﻿// ConnectionPool.cpp
#include "ConnectionPool.h"

#include <QDebug>
#include <QtSql>
#include <QStack>
#include <QString>
#include <QMutex>
#include <QSemaphore>
#include <QMutexLocker>


ConnInfo_Db ConnectionPool::s_db_conninfo;
QMutex ConnectionPool::m_mutex;
quint64 ConnectionPool::key = 0;

void ConnectionPool::initInfo(const ConnInfo_Db& db_conninfo)
{
    s_db_conninfo = db_conninfo;

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(db_conninfo.serverName);
    db.setDatabaseName("mysql");
    db.setUserName(db_conninfo.userName);
    db.setPassword(db_conninfo.password);

    if (db.open()) {
        QSqlQuery query;
        if (!query.exec("CREATE DATABASE IF NOT EXISTS " + db_conninfo.dbName)) {
            qDebug() << "Error creating database:" << query.lastError().text();
        }
        else {
            qDebug() << "Database created successfully";
        }
        db.close();
    }
    else {
        qDebug() << "Error opening database:" << db.lastError().text();
    }

}

QSqlDatabase ConnectionPool::openConnection() 
{
    QMutexLocker locker(&ConnectionPool::m_mutex);
    key = key + 1;

    if (key > 10000000)
        key = 0;

    QString connect_name = QString("C%1").arg(key);

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", connect_name);
    db.setHostName(s_db_conninfo.serverName);
    db.setDatabaseName(s_db_conninfo.dbName);
    db.setUserName(s_db_conninfo.userName);
    db.setPassword(s_db_conninfo.password);
    db.setPort(s_db_conninfo.port.toInt());
    db.setConnectOptions("MYSQL_OPT_CONNECT_TIMEOUT=3;MYSQL_OPT_READ_TIMEOUT=3;MYSQL_OPT_WRITE_TIMEOUT=3");

    if (!db.open()) {
        qDebug() << "Open datatabase error:" << db.lastError().text();
        return QSqlDatabase();
    }

    return db;
}

void ConnectionPool::closeConnection(QSqlDatabase connection) {
    //
}